//
//  AddPartListSubView.m
//  HondaPro_2
//
//  Created by Eric on 13-6-28.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "AddPartListSubView.h"
#import "MyAFNetWorkManager.h"
#import "MJRefresh.h"


enum btnTag
{
    isInStockBtnTag = 100
};

@interface AddPartListSubView ()<ContentViewControllerDelegate>

@property(nonatomic,strong)UIButton *repairGroupBtn;
@property(nonatomic,strong)UIButton *chargeDiffBtn;
@property(nonatomic,strong)UIButton *leibieBtn;
@property(nonatomic,strong)NSMutableArray *lingjianArr;
@property(nonatomic,strong)NSString *lingjianleibieID;

@property(nonatomic,strong)UIButton *projectTypeBtn;

/** 收费区分列表 */
@property(nonatomic,strong)NSMutableDictionary *chargeDiff;
@property(nonatomic,strong)NSMutableArray *chargeDiffKeys;
@property(nonatomic,strong)NSMutableDictionary *chargeDiffCodeDic;
/** 维修车型组数据列表 */
@property(nonatomic,strong)NSMutableArray *arrDisDataForCarType;
@property(nonatomic,strong)NSMutableDictionary *carTypeDic;
@property(nonatomic,weak)UITextField *priceTxt;

/** 维修项目 */
@property(nonatomic,strong)NSMutableArray *projectTypeNames;
@property(nonatomic,strong)NSMutableDictionary *projectTypeNameDic;
@property(nonatomic,strong)NSMutableArray *chargeTypeCodes;//维修项目对应的收费区分

/** 维修分类 */
@property(nonatomic,strong)NSMutableArray *repairTypeNames;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,strong)UIButton *repairTypeBtn;

/** 销售价格 */
@property(nonatomic,assign)double salesPrice;
/** 索赔价格 */
@property(nonatomic,assign)double claimPrice;


//按照零件号、零件名、有无库存进行搜索，返回零件列表
-(NSArray *)searchThePartListByPartCode:(NSString *)partCode andPartName:(NSString *)partChinaName andIsInStock:(NSString *)isInstock withPartList:(NSArray *)arrPartList;

@end

@implementation AddPartListSubView
@synthesize arrOriginalDataForRepairType = _arrOriginalDataForRepairType;
@synthesize arrOriginalDataForServiceType = _arrOriginalDataForServiceType;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        [self createStaticLbl];
        [self createTextView];
        [self createBtn];
        [self createTableViewDis];
        
        _lingjianArr = [NSMutableArray arrayWithCapacity:5];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChange:) name:UITextFieldTextDidChangeNotification object:nil];
    }
    return self;
}
-(NSMutableArray *)repairTypeNames{
    if (_repairTypeNames == nil) {
        _repairTypeNames= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_ITEM"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeNames addObject:name];
            [_repairTypeDic setObject:val forKey:name];
        }
    }
    return _repairTypeNames;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    NSLog(@"drawRect AddPartListSubView ...");
    
    [self freshenTableViewDis];
}

#pragma mark - 创建控件

-(void)createStaticLbl
{
    //创建label
    [self setupLabelWithTitle:@"零件编号:" frame:CGRectMake(0, 0, 100, 30)];
    
    [self setupLabelWithTitle:@"拼音代码:" frame:CGRectMake(380, 40, 70, 30)];
    
    [self setupLabelWithTitle:@"零件名称:" frame:CGRectMake(0, 40, 100, 30)];
    
    [self setupLabelWithTitle:@"零件类别:" frame:CGRectMake(380, 0, 70, 30)];

    [self setupLabelWithTitle:@"数量:" frame:CGRectMake(0, 400, 60, 30)];

    [self setupLabelWithTitle:@"销售价格:" frame:CGRectMake(220, 400, 70, 30)];
    
    [self setupLabelWithTitle:@"金额:" frame:CGRectMake(470, 400, 70, 30)];
    
    [self setupLabelWithTitle:@"维修项目:" frame:CGRectMake(0, 450, 70, 30)];
    
    [self setupLabelWithTitle:@"收费区分:" frame:CGRectMake(440, 450, 70, 30)];
}

-(void)setupLabelWithTitle:(NSString *)title frame:(CGRect)frame{
    UILabel *repairIdLbl = [[UILabel alloc] initWithFrame:frame];
    repairIdLbl.textColor = [UIColor grayColor];
    repairIdLbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    repairIdLbl.text = title;
    [self addSubview:repairIdLbl];
}

-(void)createTextView
{
    UIView * repairGroupBtnBg = [[UIView alloc] initWithFrame:CGRectMake(91, 2, 150, 30)];
    repairGroupBtnBg.backgroundColor = [UIColor grayColor];
    //[self addSubview:repairGroupBtnBg];
    
    [self setupDropdownLabelWithFrame:CGRectMake(451, 1, 200, 34)];
    
    self.leibieBtn = [self setupSelectButtonWithFrame:CGRectMake(451, 1, 200, 34) method:@selector(leibieBtnPressed:)];
    
    //self.repairGroupBtn = [self setupSelectButtonWithFrame:CGRectMake(90, 0, 152, 34) method:@selector(dropdownBtnTapped:)];
    
    //收费区分
    UIView * chargeDiffBtnBg = [[UIView alloc] initWithFrame:CGRectMake(521, 452, 150, 30)];
    chargeDiffBtnBg.backgroundColor = [UIColor grayColor];
    [self addSubview:chargeDiffBtnBg];
    
    self.chargeDiffBtn = [self setupSelectButtonWithFrame:CGRectMake(520, 450, 152, 34) method:@selector(dropdownBtnTapped:)];
    self.chargeDiffBtn.enabled = NO;
    
    //维修项目
    UIView * projectTypeBg = [[UIView alloc] initWithFrame:CGRectMake(81, 452, 344, 30)];
    projectTypeBg.backgroundColor = [UIColor grayColor];
    [self addSubview:projectTypeBg];
    self.projectTypeBtn = [self setupSelectButtonWithFrame:CGRectMake(77, 450, 352, 34) method:@selector(dropdownBtnTapped:)];
    

    lingjianNameField = [self setupTextFieldWithFrame:CGRectMake(90, 0, 240, 30)];
    
    groupCodeTxt = [self setupTextFieldWithFrame:CGRectMake(450, 40, 200, 30)];
    
    groupNameTxt = [self setupTextFieldWithFrame:CGRectMake(90, 40, 240, 30)];
    
    countTxt = [self setupTextFieldWithFrame:CGRectMake(60, 400, 150, 30)];
    countTxt.keyboardType = UIKeyboardTypeNumberPad;
    countTxt.text = @"1";
    
    self.priceTxt = [self setupTextFieldWithFrame:CGRectMake(300, 400, 150, 30)];
    self.priceTxt.text = @"0";
    self.priceTxt.keyboardType = UIKeyboardTypeNumberPad;
    self.priceTxt.enabled = NO;
    self.priceTxt.backgroundColor = [UIColor lightGrayColor];
    self.priceTxt.textColor = [UIColor darkGrayColor];
    
    amountTxt = [self setupTextFieldWithFrame:CGRectMake(520, 400, 150, 30)];
    amountTxt.enabled = NO;
    amountTxt.text = @"0";
    amountTxt.backgroundColor = [UIColor lightGrayColor];
    amountTxt.textColor = [UIColor darkGrayColor];
    
    countTxt.delegate = self;
    self.priceTxt.delegate = self;
    
}

-(void)setupDropdownLabelWithFrame:(CGRect)frame{
    UILabel *label1 = [[UILabel alloc]initWithFrame:frame];
    [label1 setBackgroundColor:[UIColor clearColor]];
    label1.layer.borderColor = [[UIColor blackColor]CGColor];
    label1.layer.borderWidth = 1;
    [self addSubview:label1];
}

-(UITextField *)setupTextFieldWithFrame:(CGRect)frame{
    UITextField *txt = [[UITextField alloc] initWithFrame:frame];
    txt.borderStyle = UITextBorderStyleLine;
    txt.textColor = [UIColor grayColor];
    txt.font = [UIFont fontWithName:@"ArialMT" size:16];
    [self addSubview:txt];
    return txt;
}

-(void)dropdownBtnTapped:(UIButton *)sender{
    //创建下拉菜单
    [self createThePopViewControl:sender];
    if (sender == self.repairGroupBtn){
        contentCon.list = self.arrDisDataForCarType;
    }else if (sender == self.chargeDiffBtn){
        contentCon.list = self.chargeDiffKeys;
    }else if (sender == self.projectTypeBtn){
        contentCon.list = self.projectTypeNames;
    }
    [contentCon.myTableView reloadData];
}
-(void)createBtn
{
    
    [self setupButtonWithTitle:@"查询" frame:CGRectMake(804, 0, 120, 30) method:@selector(chaxunBtnPressed:)];
    
    
    [self setupButtonWithTitle:@"清空" frame:CGRectMake(804, 40, 120, 30) method:@selector(qingkongBtnPressed:)];
    
    [self setupButtonWithTitle:@"确定新增" frame:CGRectMake(804, 400, 120, 30) method:@selector(lingjiandengluBtnPressed:)];
    
    [self setupLabelWithTitle:@"维修分类:" frame:CGRectMake(700, 450, 80, 30)];
    self.repairTypeBtn = [self setupDropdownButtonWithFrame:CGRectMake(780, 448, 152, 40) method:@selector(dropdownTapped:)];
}
-(UIButton *)setupDropdownButtonWithFrame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setBackgroundImage:[UIImage imageNamed:@"10.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    return btn;
}
-(void)dropdownTapped:(UIButton *)sender
{
    //创建下拉菜单
    [self createThePopViewControl:sender];
    NSArray *source = nil;
    source = self.repairTypeNames;
    contentCon.list = source;
    [contentCon.myTableView reloadData];
}
-(void)setupButtonWithTitle:(NSString *)title frame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont fontWithName:@"ArialMT" size:16];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
}

-(UIButton *)setupSelectButtonWithFrame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setBackgroundImage:[UIImage imageNamed:@"10.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    return btn;
}

-(void)createTableViewDis
{
    UILabel *bottomLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, self.frame.size.width, 50)];
    bottomLbl.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [self addSubview:bottomLbl];
    
    [self createStaticLblForTableViewDis];
    
    tableViewDis = [[UITableView alloc] initWithFrame:CGRectMake(0, 140, self.frame.size.width, 220)];
    tableViewDis.delegate = self;
    tableViewDis.dataSource = self;
    tableViewDis.backgroundColor = [UIColor clearColor];
    
    _arrPartListToDisplay = [NSMutableArray arrayWithCapacity:5];
    
    [self addSubview:tableViewDis];
    
    __unsafe_unretained UITableView *tableView = tableViewDis;
    
    // 下拉刷新
    //    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //
    //
    //        [tableView.mj_header endRefreshing];
    //    }];
    
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
        
        [tableView.mj_footer endRefreshing];
    }];
}

- (void)footerRefresh
{
    _nCurrentRowSel = -1;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
    
    NSString *group = lingjianNameField.text;
    NSString *groupCode = groupCodeTxt.text;
    NSString *groupName = groupNameTxt.text;
    if (group.length>0) {
        [param setObject:group forKey:@"PART_NO"];
    }
    if (groupCode.length>0) {
        [param setObject:groupCode forKey:@"SPELL_CODE"];
    }
    if (groupName.length>0) {
        [param setObject:[groupName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PART_NAME"];
    }
    
    [param setValue:_lingjianleibieID forKey:@"PART_GROUP_CODE"];
    [param setObject:[NSString stringWithFormat:@"%d",_arrPartListToDisplay.count] forKey:@"FROM"];
    [param setObject:[NSString stringWithFormat:@"%d",_arrPartListToDisplay.count+10] forKey:@"TO"];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
    [MyAFNetWorkManager postWithParam:param andAction:@"CHOOSE_PART_STOCK_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        if (!error) {
            _arrPartListToDisplay = obj[@"TM_PART_STOCK"];
            //刷新表单
            [tableViewDis reloadData];
        }else{
            NSLog(@"%@",error);
        }
        
    }];
    
}

//创建静态label for tableViewDis
-(void)createStaticLblForTableViewDis
{
    NSArray *arrForAllKeys = [NSArray arrayWithObjects:
                              @"STORAGE_CODE",
                              @"PART_NO",
                              @"PART_NAME",
                              @"PART_PRICE",
                              @"PART_QUANTITY",
                              nil];
    
    NSDictionary *dicForStaticLabelsText = [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"仓库代码",@"STORAGE_CODE",
                                            @"配件代码",@"PART_NO",
                                            @"配件名称",@"PART_NAME",
                                            @"配件价格",@"PART_PRICE",
                                            @"配件数量",@"PART_QUANTITY",
                                            nil];
    
    NSDictionary *dicForStaticLabelsRect = [NSDictionary dictionaryWithObjectsAndKeys:
                                            [NSValue valueWithCGRect:CGRectMake(0, 90, 239, 50)],@"STORAGE_CODE",
                                            [NSValue valueWithCGRect:CGRectMake(240, 90, 152, 50)],@"PART_NO",
                                            [NSValue valueWithCGRect:CGRectMake(393, 90, 305, 50)],@"PART_NAME",
                                            [NSValue valueWithCGRect:CGRectMake(698, 90, 100, 50)],@"PART_PRICE",
                                            [NSValue valueWithCGRect:CGRectMake(798, 90, 124, 50)],@"PART_QUANTITY",
                                            nil];
    
    for (int i = 0; i<[arrForAllKeys count]; i++)
    {
        UILabel *lbl = [[UILabel alloc] initWithFrame:[[dicForStaticLabelsRect objectForKey:[arrForAllKeys objectAtIndex:i]] CGRectValue]];
        lbl.backgroundColor = [UIColor clearColor];
        lbl.font = [UIFont systemFontOfSize:16];
        lbl.text = [dicForStaticLabelsText objectForKey:[arrForAllKeys objectAtIndex:i]];
        lbl.textColor = [UIColor grayColor];
        lbl.textAlignment = NSTextAlignmentCenter;
        [self addSubview:lbl];
    }
}

#pragma mark - tableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arrPartListToDisplay count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    mm_addPartListToIndicationUserDefinedCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (nil == cell)
    {
        cell = [[mm_addPartListToIndicationUserDefinedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    //cell的风格是：浅浅灰色和浅灰色间隔出现，第一行是浅灰色
    NSInteger row = [indexPath row];
    switch (row%2)
    {
        case 0:
            //浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
            break;
        case 1:
            //浅浅灰色
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            break;
            
        default:
            break;
    }
    
    //给cell上赋值
    if (row<[_arrPartListToDisplay count])
    {
        for (int i = 0; i<[cell.arrAllKeysOnCell count]; i++)
        {
            NSString *key = cell.arrAllKeysOnCell[i];
            NSDictionary *data = _arrPartListToDisplay[row];
            NSString *text = nil;
            if ([key isEqualToString:@"PART_QUANTITY"]) {
                text = [data[key] stringValue];
            }else{
                text = [NSString stringWithFormat:@"%@",data[key]];
            }
            ((UILabel *)[cell.dicAllLblsOnCell objectForKey:key]).text = text;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    else
    {
        for (int i = 0; i<[cell.arrAllKeysOnCell count]; i++)
        {
            ((UILabel *)[cell.dicAllLblsOnCell objectForKey:[cell.arrAllKeysOnCell objectAtIndex:i]]).text = @"";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

#pragma mark - tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];

    if (row<[_arrPartListToDisplay count])
    {
        NSDictionary *selectData = _arrPartListToDisplay[row];
        self.salesPrice = [selectData[@"SALES_PRICE"]doubleValue];
        self.claimPrice = [selectData[@"CLAIM_PRICE"]doubleValue];
        [self setPriceWithChargeDiffCode:nil];
        [self computeAmount];
        //设置选中行
        _nCurrentRowSel = row;
    }
}

-(void)textFieldValueChange:(NSNotification *)note{
    [self computeAmount];
}

-(void)computeAmount{
    double count = [countTxt.text doubleValue];
    double price = [self.priceTxt.text doubleValue];
    amountTxt.text = [NSString stringWithFormat:@"%.2f",count * price];
}

- (void)leibieBtnPressed:(UIButton *)btn
{
    if (!contentCon) {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    contentCon.delegate = self;
    contentCon.btnSender=btn;
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:242 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(btn.frame.size.width, 160)];
    [popCon presentPopoverFromRect:CGRectMake(95, 0, 135, 20) inView:btn permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    
    NSArray *zidianArr=[self readershuDICimform][@"TM_PART_TYPE"];
    NSMutableArray *modelArr = [[NSMutableArray alloc]init];
    [_lingjianArr removeAllObjects];
    
    for(NSDictionary *dic in zidianArr)
    {
        [modelArr addObject:dic[@"NAME"]];
        [_lingjianArr addObject:dic[@"CODE"]];
    }
    [modelArr insertObject:@"< 空 >" atIndex:0];
    contentCon.list = modelArr;
    
    [contentCon.myTableView reloadData];
}

#pragma mark - 刷新控件内容

-(void)freshenTableViewDis
{
    //该页面的入口方法
    
    /*
     初始化操作是：
     （1）请求数据，请求所有的零件信息赋给 属性
     */
    
//    [self jsonParseFromJsonSearchParts];
    
    _nCurrentRowSel = -1;
    
    [tableViewDis reloadData];
}

#pragma mark - 回调方法

-(void)xianshichengbenjiaBtnPressed:(id)sender
{
    NSLog(@"xianshichengbenjiaBtnPressed !!!");
}

-(void)chaxunBtnPressed:(id)sender
{
    _nCurrentRowSel = -1;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
    
    NSString *group = lingjianNameField.text;
    NSString *groupCode = groupCodeTxt.text;
    NSString *groupName = groupNameTxt.text;
    if (group.length>0) {
        [param setObject:group forKey:@"PART_NO"];
    }
    if (groupCode.length>0) {
        [param setObject:groupCode forKey:@"SPELL_CODE"];
    }
    if (groupName.length>0) {
        [param setObject:[groupName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"PART_NAME"];
    }
    
    [param setValue:_lingjianleibieID forKey:@"PART_GROUP_CODE"];
    [param setObject:@"1" forKey:@"FROM"];
    [param setObject:@"10" forKey:@"TO"];
    
    [SVProgressHUD showWithStatus:@"请等待...."];
    [MyAFNetWorkManager postWithParam:param andAction:@"CHOOSE_PART_STOCK_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        [SVProgressHUD dismiss];
        if (!error) {
            _arrPartListToDisplay = obj[@"TM_PART_STOCK"];
            //刷新表单
            [tableViewDis reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:@"查询异常"];
            _arrPartListToDisplay = nil;
            [tableViewDis reloadData];
            NSLog(@"%@",error);
        }
        
    }];
}

-(void)qingkongBtnPressed:(id)sender
{
    
    //设置界面显示的数据
    groupNameTxt.text = @"";
    countTxt.text = @"1";
    amountTxt.text = @"0";
}

-(void)lingjiandengluBtnPressed:(id)sender
{
    NSString *msg = [self getErrorMsg];
    if (msg) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
    NSMutableDictionary *seletedData = _arrPartListToDisplay[_nCurrentRowSel];
    NSString *chargeDiffVal = self.chargeDiff[self.chargeDiffBtn.titleLabel.text];
    double price = [self.priceTxt.text doubleValue];
    int count = [countTxt.text integerValue];
    double amout = [amountTxt.text doubleValue];
    if (!chargeDiffVal) {
        chargeDiffVal = @"";
    }
    [seletedData setObject:@"" forKey:@"ITEM_ID"];//id
    [seletedData setObject:@"A" forKey:@"STATUS"];//状态
    [seletedData setObject:@(self.discount) forKey:@"DISCOUNT"];//折扣
    seletedData[@"REPAIR_TYPE_CODE"]=self.repairTypeDic[self.repairTypeBtn.currentTitle];
    [seletedData setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
    seletedData[@"LABOUR_NAME"] = self.projectTypeBtn.titleLabel.text;//维修项目名称
    seletedData[@"LABOUR_CODE"] = self.projectTypeNameDic[self.projectTypeBtn.titleLabel.text];//维修项目代码
    [seletedData setObject:@(price) forKey:@"PART_SALES_PRICE"];//销售价格
    [seletedData setObject:@(count) forKey:@"PART_QUANTITY"];//数量
    [seletedData setObject:@(amout) forKey:@"PART_SALES_AMOUNT"];//金额
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    [modelIns.partList addObject:seletedData];
    //更新完数据后刷新界面
    [[NSNotificationCenter defaultCenter] postNotificationName:SECOND_PART_LIST_MSG_ object:nil];
    [SVProgressHUD showInfoWithStatus:@"新增成功"];
}

-(NSString *)getErrorMsg{
    NSString *msg = nil;
    if (_nCurrentRowSel == -1) {
        msg = @"请选择一行数据！";
    }else if (self.priceTxt.text.length<=0){
        msg = @"请输入销售价格！";
    }else if ([countTxt.text doubleValue]<=0){
        msg = @"数量不允许为0";
    }else if (self.projectTypeBtn.titleLabel.text.length<=0){
        msg = @"请选择维修项目";
    }else if (self.chargeDiffBtn.currentTitle.length<=0){
        msg = @"收费区分不能为空";
    }else if (self.repairTypeBtn.currentTitle.length<=0){
        msg = @"选择维修分类";
    }
    return msg;
}

/*just for test*/
-(void)jsonParseFromJsonSearchParts
{
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"JsonFileForSearchPartsInventory" ofType:@"json"];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[HelpClass jsonParseByJsonFileStr:jsonFilePath]];
    
    NSLog(@"dic = %@",dic);
    
    //dic是从json file中解析出来的数据，更新该类中的属性
    _arrPartList = [NSMutableArray arrayWithArray:[dic objectForKey:MM_PARTS_SEARCH_LIST_KEY_STR_]];
    _arrPartListToDisplay = [NSMutableArray arrayWithArray:_arrPartList];
}
/*just for test*/

//按照零件号、零件名、有无库存进行搜索，返回零件列表
-(NSArray *)searchThePartListByPartCode:(NSString *)partCode andPartName:(NSString *)partChinaName andIsInStock:(NSString *)isInstock withPartList:(NSArray *)arrPartList
{
    NSMutableArray *arrTmp = [NSMutableArray array];
    for (int i = 0; i<[_arrPartList count]; i++)
    {
        NSString *partCodeTmp = [[_arrPartList objectAtIndex:i] objectForKey:@"STORAGE_CODE"];
        NSString *partChinaNameTmp = [[_arrPartList objectAtIndex:i] objectForKey:@"PART_NO"];
        NSString *isInStockTmp = (NSInteger)[[[arrPartList objectAtIndex:i] objectForKey:MM_PARTS_PART_STORAGE_QTY_KEY_STR_] integerValue] > 0 ? @"1":@"0";
        NSDictionary *dicTmp = [_arrPartList objectAtIndex:i];
        
        if (
            (
             nil == partCode
             ||
             [partCode isEqualToString:@""]
             ||
             [partCode isEqualToString:partCodeTmp]
            )
            &&
            (
            nil == partChinaName
             ||
             [partChinaName isEqualToString:@""]
             ||
             [partChinaName isEqualToString:partChinaNameTmp]
            )
            &&
            (
            nil == isInstock
             ||
             [isInstock isEqualToString:@""]
             ||
             [isInstock isEqualToString:isInStockTmp]
            )
            )
        {
            [arrTmp addObject:dicTmp];
        }
    }
    return arrTmp;
}

//设置按钮的状态
-(void)setUpTheStateBtnByBtn:(UIButton *)btn andState:(BOOL)state
{
    if (YES == state)
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    else
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    }
}


//tableView的ScrollView代理方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate //判断上拉的偏移量
{
    //    if (detailedtabelView.contentOffset.y > _imageArray.count * 80 - detailedtabelView.bounds.size.height + 80)
    //    {
    //        NSLog(@"%f", detailedtabelView.contentOffset.y);
    //        [self asynGetRequest];
    //    }
    
    //发送请求数据的消息
    //    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    //    NSArray *arr = modelIns.arrForSearchPartsInventory;
    
    //    if (self.tableViewDis.contentOffset.y > arr.count * 50-)
    //    {
    //        NSLog(@"hahahah!!!");
    //    }
    
    //上拉刷新
    if(scrollView.contentSize.height - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom) <= -52.0f && scrollView.contentOffset.y > 0)
    {
        
    }
}

//判断要添加的零件是不是已经存在
-(BOOL)thePartNotRepeat
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *arrTmpTmp = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"partList"];
    
    NSLog(@"%@",arrTmpTmp);
    
    for (int i = 0; i<[arrTmpTmp count]; i++)
    {
        if (
            [[[arrTmpTmp objectAtIndex:i] objectForKey:@"partCode"] isEqualToString:[[_arrPartListToDisplay objectAtIndex:_nCurrentRowSel] objectForKey:@"partCode"]]
            )
        {
            return NO;
        }
    }
    
    return YES;
}

//判断作业指示的 服务类型 是否是保修
-(BOOL)isWarrantyByServiceInIndication
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *str = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"serviceType"];
    NSRange range = [[self getNameByServiceId:str] rangeOfString:@"保修"];
    if (range.length == [@"保修" length])
    {
        return YES;
    }
    return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.keyboardType = UIKeyboardTypeNumberPad;
    
//    int offset = 350;//键盘高度350
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    float width = self.view.frame.size.width;
//    float height = self.view.frame.size.height;
//    if(offset > 0)
//    {
//        CGRect rect = CGRectMake(0.0f, -offset,width,height);
//        self.view.frame = rect;
//    }
//    [UIView commitAnimations];
    
    //将scrollView上托到最大位置
    [[NSNotificationCenter defaultCenter] postNotificationName:@"mm_addAndModifyViewControllerScrollViewScroll" object:nil];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@".0123456789\n"]invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
    BOOL canChange = [string isEqualToString:filtered];
    return canChange;
}

//得到列表中的最大序号
-(NSInteger)getTheMaxNumber
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSArray *arrTmp = [[[[modelIns.arrForResults objectAtIndex:modelIns.nRowForResults] objectForKey:@"indicationList"] objectAtIndex:modelIns.nRowForIndicationList] objectForKey:@"partList"];
    
    NSInteger nMaxNumber = 0;
    
    for (int i = 0; i<[arrTmp count]; i++)
    {
        NSString *strTmp = [[arrTmp objectAtIndex:i] objectForKey:MM_PART_PART_NUMBER_KEY_STR_];
        nMaxNumber = nMaxNumber < [strTmp integerValue] ? [strTmp integerValue] : nMaxNumber;
    }
    
    return nMaxNumber;
}

//根据ID取名字
-(NSString *)getNameByServiceId:(NSString *)serviceId
{
    for (int i = 0; i<[self.arrOriginalDataForServiceType count]; i++)
    {
        NSString *strId = [[self.arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeId"];
        NSString *strName = [[self.arrOriginalDataForServiceType objectAtIndex:i] objectForKey:@"serviceTypeName"];
        if ([serviceId isEqualToString:strId])
        {
            return strName;
        }
    }
    return @"";
}

-(NSString *)getNameByRepairId:(NSString *)RepairId
{
    for (int i = 0; i<[self.arrOriginalDataForRepairType count]; i++)
    {
        NSString *strId = [[self.arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeId"];
        NSString *strName = [[self.arrOriginalDataForRepairType objectAtIndex:i] objectForKey:@"repairTypeName"];
        if ([RepairId isEqualToString:strId])
        {
            return strName;
        }
    }
    return @"";
}

//创建下拉菜单方法
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    
    popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

//弹出的回调方法
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *key = nil;
    if (btn == self.repairGroupBtn){
        key = self.arrDisDataForCarType[row];
    }else if (btn == self.chargeDiffBtn){
        key = self.chargeDiffKeys[row];
        NSString *code = self.chargeDiff[key];
        [self setPriceWithChargeDiffCode:code];
        [self computeAmount];
    }else if (btn == self.projectTypeBtn){
        key = self.projectTypeNames[row];
        NSString *code = self.chargeTypeCodes[row];//获取收费区分代码
        [self chargeDiffKeys];
        NSString *chargeTypeName = self.chargeDiffCodeDic[code];
        [self.chargeDiffBtn setTitle:chargeTypeName forState:UIControlStateNormal];
//        [self setPriceWithChargeDiffCode:code];
//        [self computeAmount];
    }else if (btn == self.repairTypeBtn){
        key = self.repairTypeNames[row];
        NSString *code = self.repairTypeNames[row];//获取收费区分代码
        NSString *chargeTypeName = self.repairTypeDic[code];
        [self.repairTypeBtn setTitle:chargeTypeName forState:UIControlStateNormal];
        //        [self setPriceWithChargeDiffCode:code];
        //        [self computeAmount];
    }
    
    [btn setTitle:key forState:UIControlStateNormal];
    
    if (btn==self.leibieBtn) {
        if (row==0) {
            [self.leibieBtn setTitle:@"< 空 >" forState:UIControlStateNormal];
        }
        else{
            [self.leibieBtn setTitle:contentCon.list[row] forState:UIControlStateNormal];
            self.lingjianleibieID = [_lingjianArr objectAtIndex:row];
        }
    }
    
    //清空数据，退出控件
    [popCon dismissPopoverAnimated:YES];
    popCon = nil;
}

-(void)setPriceWithChargeDiffCode:(NSString *)code{
    //如果收费区分是首保、保修、市场活动、PDI、配件索赔，那么配件销售价就去索赔价，反之去销售价
    double price = 0;
    if ([code isEqualToString:@"S002"]||[code isEqualToString:@"S004"]||[code isEqualToString:@"S008"]||[code isEqualToString:@"S009"]||[code isEqualToString:@"S010"]) {
        price = self.claimPrice;
    }else{
        price = self.salesPrice;
    }
    self.priceTxt.text = [NSString stringWithFormat:@"%.2f",price];
}

#pragma mark -懒加载
/** 收费区分 */
-(NSMutableArray *)chargeDiffKeys{
    if (_chargeDiffKeys == nil) {
        _chargeDiffKeys= [NSMutableArray array];
        _chargeDiff = [NSMutableDictionary dictionary];
        _chargeDiffCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_CHARGE_PARTITION"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_chargeDiffKeys addObject:name];
            [_chargeDiff setObject:val forKey:name];
            [_chargeDiffCodeDic setObject:name forKey:val];
        }
    }
    return _chargeDiffKeys;
}

/** 维修车型组 */
-(NSMutableArray *)arrDisDataForCarType{
    if (_arrDisDataForCarType == nil) {
        _arrDisDataForCarType= [NSMutableArray array];
        _carTypeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_MODEL_LABOUR"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            if (name&&val) {
                [_arrDisDataForCarType addObject:name];
                [_carTypeDic setObject:val forKey:name];
            }
        }
    }
    return _arrDisDataForCarType;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

/** 维修项目 */
-(NSMutableArray *)projectTypeNames{
    if (_projectTypeNames == nil) {
        NSMutableArray *names = [NSMutableArray array];
        _chargeTypeCodes = [NSMutableArray array];
        _projectTypeNameDic = [NSMutableDictionary dictionary];
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        NSArray *arrRepairItemList = modelIns.repairProjects;
        NSString *projetName = nil;
        for (NSDictionary *dic in arrRepairItemList) {
            projetName = dic[@"LABOUR_NAME"];
            if (projetName.length>0) {
                [names addObject:projetName];
                _projectTypeNameDic[projetName] = dic[@"LABOUR_CODE"];
                if (dic[@"CHARGE_PARTITION_CODE"]) {
                    [_chargeTypeCodes addObject:dic[@"CHARGE_PARTITION_CODE"]];
                }else{
                    [_chargeTypeCodes addObject:@""];
                }
            }
        }
        _projectTypeNames = names;
    }
    
    return _projectTypeNames;
}
@end
